//
//  ViewController.m
//  iMessage
//
//  Created by kare on 14-3-4.
//  Copyright (c) 2014年 kare. All rights reserved.
//

#import "MainViewController.h"
#import "ASIFormDataRequest.h"
#import "ManagerObjectData.h"
#import "RegisterViewController.h"
#import "ShowMsgBox.h"
#import "UserInformationViewController.h"
#import "HelpPro.h"
#import "notify.h"


//#define PLISTRURL @"/Applications/user_preferences.plist"

@interface MainViewController ()

@property (nonatomic ,weak) IBOutlet UITextField *ui_userNameField;
@property (nonatomic ,weak) IBOutlet UITextField *ui_passwdField;
@property (nonatomic ,weak) IBOutlet UIView *ui_topView;
@property (nonatomic ,weak) IBOutlet UIButton *ui_loginBtn;
@end

@implementation MainViewController



- (IBAction)onLogin:(id)sender
{
    [self onHideKeyBoard];
    
    
    if (!validateMobile(self.ui_userNameField.text))
    {
        showView(@"手机号码不正确");
        double delayInSeconds = .8;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.ui_userNameField becomeFirstResponder];
        });
        
        return ;
    }
    else if([self.ui_passwdField.text length] == 0)
    {
        showView(@"密码不能为空");
        
        double delayInSeconds = .8;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.ui_passwdField becomeFirstResponder];
        });
        return ;
    }
    
    [self onLogin];
}

- (void)onHideKeyBoard
{
    if ([self.ui_passwdField isFirstResponder])
    {
        [self.ui_passwdField resignFirstResponder];
    }
    if ([self.ui_userNameField isFirstResponder])
    {
        [self.ui_userNameField resignFirstResponder];
    }
}

- (IBAction)onRegister:(id)sender
{
    [self onHideKeyBoard];
    
    RegisterViewController *registerV =[[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:registerV];
//    [nav setNavigationBarHidden:YES];
    [self.navigationController pushViewController:registerV animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self onCreatePlist];
}

- (void)onCreatePlist
{
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSString *plistPath = PLISTRURL;
    
    if (![fm fileExistsAtPath:plistPath])
    {
       [fm createFileAtPath:plistPath contents:nil attributes:nil];
    }
    
        // 6e59d9f00dfb6abc64373603b7777e6b
//    NSString *urlString = [NSString stringWithFormat:@"%@task",BASICE_URL_TOIMESSAGE];
//    
//    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    
//    NSLog(@"rul = %@",urlString);
//    
//    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
//    [requestForm setPostValue:@"6e59d9f00dfb6abc64373603b7777e6b" forKey:@"token"];
//    [requestForm startSynchronous];
//    
//    NSLog(@"requestForm = %@\n",[requestForm responseString]);
    
    
//    NSArray *array = [NSArray arrayWithObjects:@"wo shi",
//                      @"wo shi",
//                      @"wo shi",
//                      @"wo shi",nil];
//    [array writeToFile:plistPath atomically:YES];
//    
//    NSArray *arra  = [NSArray arrayWithContentsOfFile:plistPath];
//    
//    NSLog(@"写入的东西");
//    NSLog(@"arra = %@",arra);
//    
//    //开始创建文件
    
}


- (void)onLogin
{
    showViewInView(self.view,@"请求中......");
    
    NSString *urlString = [NSString stringWithFormat:@"%@login",BASICE_URL_TOIMESSAGE];
//    NSString *urlString = @"http://sim.xayoudao.com/sim/index.php?r=api/login";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [requestForm setPostValue:self.ui_passwdField.text forKey:@"password"];
    [requestForm setPostValue:self.ui_userNameField.text forKey:@"mobile"];
    [requestForm startSynchronous];
    
    hideViewInView(self.view);
    
    NSLog(@"[requestForm responseData] = %@",[requestForm responseString]);
    
    NSMutableDictionary *dicB = [ManagerObjectData getCurrentData:[requestForm responseData]];
    
    NSLog(@"dic  =%@",dicB);
    
    if (dicB != nil && [[dicB objectForKey:@"code"] intValue] != 1000)
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSDictionary *dic = [dicB objectForKey:@"data"];
            
            NSLog(@"cao cao cao cao cao cao");
            
            if (dic != nil)
            {
                NSLog(@"cao cao cao cao cao cao");
                
                NSString *userToken = [dic  objectForKey:@"token"];
                
                int  Level = [[dic objectForKey:@"level"] intValue];
                
                NSString *mobile = [dic objectForKey:@"mobile"];
                
                [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:Level] forKey:@"UserLevel"];
                [[NSUserDefaults standardUserDefaults] setObject:userToken forKey:@"UserToken"];
                [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"UserMobile"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                NSArray *array = [NSArray arrayWithObject:userToken];
                [array writeToFile:PLISTRURL atomically:YES];
                
                // 触发通知了
                NSLog(@"发通知了notify_post");
                notify_post("com.betetui.settings_changed");
                NSLog(@"发通知了notify_post");
            }
        });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self goUserCenter];
            self.ui_passwdField.text = nil;
            self.ui_userNameField.text = nil;
        });
    }
    else
    {
        showView(@"登录失败");
    }
}

- (void)goUserCenter
{
    UserInformationViewController *user = [[UserInformationViewController alloc] initWithNibName:@"UserInformationViewController" bundle:nil];
    [self.navigationController pushViewController:user animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"sfsdf");
    [textField resignFirstResponder];
    [self onLogin:nil];
    return YES;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
